package com.example.filter;

import com.example.service.impl.LoginUser;
import com.example.utils.JwtUtil;
import com.example.utils.RedisCashe;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @author: 21050134
 * @date: 2023/11/8 17:42
 * @description:
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

	@Autowired
	private RedisCashe redisCashe;


	@Override
	protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {

		//获取token
		String token = httpServletRequest.getHeader("token");

		if (!StringUtils.hasText(token)) {
			//放行
			filterChain.doFilter(httpServletRequest, httpServletResponse);
			return;
		}

       //解析token
		String userid;
		try {
			Claims claims = JwtUtil.parseJWT(token);
			userid = claims.getSubject();
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("token非法");
		}
        //从redis中获取用户信息
		String redisKey = "login:" + userid;
		LoginUser loginUser = redisCashe.getCacheObject(redisKey);
		if(Objects.isNull(loginUser)){
			throw new RuntimeException("用户未登录");
		}
		//封装Authentication对象存入SecurityContextHolder
		//TODO 获取权限信息封装到Authentication中

		UsernamePasswordAuthenticationToken authenticationToken =
				new UsernamePasswordAuthenticationToken(loginUser,null,null);

		SecurityContextHolder.getContext().setAuthentication(authenticationToken);
		//放行
		filterChain.doFilter(httpServletRequest, httpServletResponse);

	}
}
